package cn.edu.hit.core.message;

import cn.edu.hit.HttpRequestor2;
import cn.edu.hit.HttpRequestorWithToken;
import cn.edu.hit.core.Document;
import cn.edu.hit.core.Pair;
import cn.edu.hit.core.conf.ConfigureLoader;
import cn.edu.hit.core.db.*;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import net.sf.json.groovy.GJson;
import net.sf.json.util.JSONUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * 使用历史数据接口，对每一项生成一个Map key--timestamp value--signalValue
 */
public final class HarbinElectricGroupAdapter extends MessageAdapterHelper2<Map> {
    static Logger logger = LoggerFactory.getLogger(HarbinElectricGroupAdapter.class);

    @Override
    public boolean accept(String type) {
        return "HEC".equalsIgnoreCase(type);
    }

    private HttpRequestorWithToken requestor;
    private String token_aquire_url = "http://222.171.52.120:11185/api/v1/authorization/auth";
    private String token_aquire_user = "wangrp";
    private String token_aquire_password = "Wrp123456";
    private String token_refresh_url = "http://222.171.52.120:11185/api/v1/authorization/refresh/";
    private String feature_aquire_url = "http://222.171.52.120:11209/api/v1/app/inference4";

//    private String feature_aquire_module = "TPMotorInference";

//    private HttpRequestorWithToken.Token token = null;

    private long work_span = 10000;
    private Map<String, String> machineId2Number = new ConcurrentHashMap<>();

    {

        Document conf = ConfigureLoader.getInstance().getBaseConfigure();
        token_aquire_url = conf.getString("token_aquire_url", token_aquire_url);
        token_aquire_user = conf.getString("token_aquire_user", token_aquire_user);
        token_aquire_password = conf.getString("token_aquire_password", token_aquire_password);
        token_refresh_url = conf.getString("token_refresh_url", token_refresh_url);
        feature_aquire_url = conf.getString("feature_aquire_url", feature_aquire_url);

        requestor = HttpRequestorWithToken.getInstance(token_aquire_url, token_aquire_user, token_aquire_password, token_refresh_url);

        String WORK_SPAN = conf.getString("WORK_SPAN", "10000");
        try {
            work_span = Integer.parseInt(WORK_SPAN);
            if (work_span <= 500) {
                work_span = 500;
            }
        } catch (NumberFormatException ex) {
            logger.error("配置文件不正确，" + WORK_SPAN + "应当为大于500的整数。 ");
        }
    }

    @Override
    protected Map pretreat(Long timestamp) {
        DataConnection connection = DataConnectionLoader.getInstance();
        DataReader reader = connection.getReader();
        DBReadHelper dbHelper = new DBReadHelper(reader);
        Set<String> machineSet = configureMap.entrySet().stream()
                .map(entry -> entry.getValue().get("name").toString())
                .filter(Objects::nonNull)
                .collect(Collectors.toSet());
        for (String machineId : machineSet) {
            String machineNumber = dbHelper.getById(machineId).getString("MachineNo");
            machineId2Number.put(machineId, machineNumber);
        }

        Map<String, List<String>> jsIds = configureMap.entrySet().parallelStream().<Pair<String, String>>map(entry -> {
            Document configure = (Document) entry.getValue();
            String machineId = configure.getString("name");
            String machineNumber = machineId2Number.get(machineId);
            return Pair.of(machineNumber, configure.getString(DATA_SOURCE_ARGS));
        })
                .filter(pire -> pire.key != null)
                .collect(Collectors.groupingBy(p -> p.key, Collectors.mapping(x -> x.value, Collectors.toList())));

        if (jsIds.size() == 0)
            return new JSONObject();

        Document config = ConfigureLoader.getInstance().getBaseConfigure();

        logger.info("测点集合jsIds：{}", jsIds);

        Map<String, Map<String, Map<Long, Double>>> mapMap = new HashMap<>();

        for (String machineNumber : jsIds.keySet()) {
            Map machine2table = (Map) config.get("machine2table");
            String url = machine2table.getOrDefault(machineNumber, "http://222.171.52.120:11209/api/v1/app/inference4").toString();
            List<String> ids = jsIds.get(machineNumber);
            try {
                Map<String, Map<Long, Double>> resultMap = requestAsJson(ids, timestamp, url);
                mapMap.put(machineNumber, resultMap);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        try {
            return mapMap;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new JSONObject();
    }

    @Override
    protected Object getValue(Map data, String id, Document configure) {
        String joinSystemId = configure.getString(DATA_SOURCE_ARGS);
        Map<String, Map<String, Map<Long, Double>>> dataMap = data;
        String machineNumber = machineId2Number.get(configure.getString("name"));
        return dataMap.get(machineNumber).get(joinSystemId);
    }

    private Map requestAsJson(List<String> jsIds, Long timestamp, String feature_aquire_url) throws Exception {

//       String resultJson = requestor.getFeatures(feature_aquire_url,timestamp-work_span,timestamp,true, jsIds.toArray(new String[0]));
//       logger.info("请求地址:"+feature_aquire_url+",请求成功");
//       logger.info(resultJson);
//       JSONObject jsonObject = JSONObject.fromObject(resultJson);
//       JSONObject jsonData = jsonObject.getJSONObject("data");
        Map<String, Map<Long, Double>> valueMap = new HashMap<>();

        File file = new File("./data.json");
        String str = "";
        if (file.exists()) {
            InputStreamReader isr = new InputStreamReader(new FileInputStream(file), "utf-8");
            BufferedReader br = new BufferedReader(isr);
            String data = null;
            while ((data = br.readLine()) != null) {
                str += data;
            }
            br.close();
        }

        JSONObject jsonObject = JSONObject.fromObject(str);
        jsonObject.keySet().forEach((jsids) -> {
            valueMap.put((String) jsids, new HashMap<>());
            JSONObject timevalue = jsonObject.getJSONObject((String) jsids);
            timevalue.keySet().forEach(timeString -> {
                valueMap.get((String) jsids).put(Long.valueOf((String) timeString), timevalue.getDouble((String) timeString));
            });
        });


//         valueMap.put("H3_3_xm0769",new HashMap<>());
//         valueMap.get("H3_3_xm0769").put(Long.valueOf("20191224110154"),10.0);
//         valueMap.get("H3_3_xm0769").put(Long.valueOf("20191224110224"),20.0);
//         valueMap.get("H3_3_xm0769").put(Long.valueOf("20191224110254"),30.0);
//         valueMap.get("H3_3_xm0769").put(Long.valueOf("20191224110354"),40.0);
//         valueMap.put("H3_3_xm0768",new HashMap<>());
//         valueMap.get("H3_3_xm0768").put(Long.valueOf("20191224110154"),10.1);
//         valueMap.get("H3_3_xm0768").put(Long.valueOf("20191224110224"),20.1);
//         valueMap.get("H3_3_xm0768").put(Long.valueOf("20191224110254"),30.1);
//         valueMap.get("H3_3_xm0768").put(Long.valueOf("20191224110354"),40.1);

//        valueMap.put("TEST01X",new HashMap<>());
//        valueMap.get("TEST01X").put(Long.valueOf("20191224110154"),20.0);
//        valueMap.get("TEST01X").put(Long.valueOf("20191224110224"),20.0);
//        valueMap.get("TEST01X").put(Long.valueOf("20191224110254"),20.0);
//        valueMap.get("TEST01X").put(Long.valueOf("20191224110354"),20.0);
//
//        valueMap.put("TEST02Y",new HashMap<>());
//        valueMap.get("TEST02Y").put(Long.valueOf("20191224110154"),20.1);
//        valueMap.get("TEST02Y").put(Long.valueOf("20191224110224"),20.1);
//        valueMap.get("TEST02Y").put(Long.valueOf("20191224110254"),20.1);
//        valueMap.get("TEST02Y").put(Long.valueOf("20191224110354"),20.1);
//
//        valueMap.put("TEST03Z",new HashMap<>());
//        valueMap.get("TEST03Z").put(Long.valueOf("20191224110154"),51.1);
//        valueMap.get("TEST03Z").put(Long.valueOf("20191224110224"),51.1);
//        valueMap.get("TEST03Z").put(Long.valueOf("20191224110254"),51.1);
//        valueMap.get("TEST03Z").put(Long.valueOf("20191224110354"),51.1);


//       jsonData.keySet().forEach((timeString)->{
//           JSONArray valueArray = jsonData.getJSONArray((String) timeString);
//
//           for (int i = 0; i < valueArray.size(); i++) {
//               String str = valueArray.getString(i);
//               if(!str.equals("null")){
//                   double value = valueArray.getDouble(i);
//                   String id = jsIds.get(i);
//                   if (!valueMap.containsKey(id)){
//                       valueMap.put(id,new HashMap<>());
//                   }
//                   valueMap.get(id).put(Long.parseLong((String)timeString),value);
//               }
//           }
//       });
        return valueMap;
    }

    private Map requestAsJson2(List<String> jsIds, Long timestamp, String feature_aquire_url) throws Exception {
        String resultJson = requestor.getFeatures(feature_aquire_url, timestamp - work_span, timestamp, true, jsIds.toArray(new String[0]));
        logger.info("请求地址:" + feature_aquire_url + ",请求成功");
        logger.info(resultJson);
        JSONObject jsonObject = JSONObject.fromObject(resultJson);
        JSONObject jsonData = jsonObject.getJSONObject("data");
        Map<String, Map<Long, Double>> valueMap = new HashMap<>();
        jsonData.keySet().forEach((timeString) -> {
            JSONArray valueArray = jsonData.getJSONArray((String) timeString);

            for (int i = 0; i < valueArray.size(); i++) {
                String str = valueArray.getString(i);
                if (!str.equals("null")) {
                    double value = valueArray.getDouble(i);
                    String id = jsIds.get(i);
                    if (!valueMap.containsKey(id)) {
                        valueMap.put(id, new HashMap<>());
                    }
                    valueMap.get(id).put(Long.parseLong((String) timeString), value);
                }
            }
        });
        return valueMap;

    }
//    private Map requestAsJson(List<String> jsIds, Long timestamp,String feature_aquire_url) throws Exception {
//
//        String resultJson = requestor.getFeatures(feature_aquire_url,timestamp-work_span,timestamp,true, jsIds.toArray(new String[0]));
//        logger.info("请求地址:"+feature_aquire_url+",请求成功");
//        JSONObject jsonObject = JSONObject.fromObject(resultJson);
//        JSONObject jsonData = jsonObject.getJSONObject("data");
//        Map<String,Map<Long,Double>> valueMap = new HashMap<>();
//        jsonData.keySet().forEach((timeString)->{
//            JSONArray valueArray = jsonData.getJSONArray((String) timeString);
//            LocalDateTime dateTime = LocalDateTime.parse((String) timeString,HttpRequestor2.formatter);
//            long dateTimeStamp = dateTime.toInstant(ZoneOffset.ofHours(8)).toEpochMilli();
//            for (int i = 0; i < valueArray.size(); i++) {
//                double value = valueArray.getDouble(i);
//                String id = jsIds.get(i);
//                if (!valueMap.containsKey(id)){
//                    valueMap.put(id,new HashMap<>());
//                }
//                valueMap.get(id).put(dateTimeStamp,value);
//            }
//        });
//        return valueMap;
//    }

//    private Map requestAsJson2(List<String> jsIds, Long timestamp,String feature_aquire_url) throws Exception {
//
//        String resultJson = requestor.getFeatures(feature_aquire_url,timestamp-work_span,timestamp,true, jsIds.toArray(new String[0]));
//        logger.info("请求地址:"+feature_aquire_url+",请求成功");
//        JSONObject jsonObject = JSONObject.fromObject(resultJson);
//        JSONObject jsonData = jsonObject.getJSONObject("data");
//        Map<String,Map<Long,Double>> valueMap = new HashMap<>();
//        jsonData.keySet().forEach((timeString)->{
//            JSONArray valueArray = jsonData.getJSONArray((String) timeString);
//            LocalDateTime dateTime = LocalDateTime.parse((String) timeString,HttpRequestor2.formatter);
//            long dateTimeStamp = dateTime.toInstant(ZoneOffset.ofHours(8)).toEpochMilli();
//            for (int i = 0; i < valueArray.size(); i++) {
//                double value = valueArray.getDouble(i);
//                String id = jsIds.get(i);
//                if (!valueMap.containsKey(id)){
//                    valueMap.put(id,new HashMap<>());
//                }
//                valueMap.get(id).put(dateTimeStamp,value);
//            }
//        });
//        return valueMap;
//    }
}
